import React, { Component } from 'react'
import { Upload, Modal, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons';
import { PropTypes } from 'prop-types'
import { APIDeleteImg } from '../../api'
import { BASE_IMG_URL } from '../../utils/constants';


function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default class PictoresWall extends Component {

  static propTypes = {
    imgs: PropTypes.array
  }

  constructor(props) {
    super(props)
    // 初始化状态
    let fileList = []
    const imags = this.props.imags || []
    if(imags[0]) {
      const newImags = JSON.parse(imags)
      fileList = newImags.map((img, index) => ({
        uid: -index,
        name: img,
        status: 'done',
        url: BASE_IMG_URL + img
      }))
    }
    this.state = {
      previewVisible: false,
      previewImage: '',
      previewTitle: '',
      fileList
    };
  }



  // 获取所有已上传文件名的数组
  getImgs = () => {
    return this.state.fileList.map(file => file.name)
  }


  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };
  /*
  file: 当前操作的图片文件(上传/删除)
  fileList: 所有已上传文件对象的数组
  */
  handleChange = async ({ file, fileList }) => {
    // 一旦上传成功，将当前上传的 file 信息进行修正(name, url)
    if(file.status === 'done') {
      const result = file.response
      if(result.status === 0) {
        message.success('上传图片成功')
        const { name ,url } = result.data
        file = fileList[fileList.length-1]
        file.name = name
        file.url = url
      } else {
        message.error('上传图片失败')
      }
    } else if(file.status === 'removed') {
      const result = await APIDeleteImg(file.name)
      if(result.status === 0) {
        message.success('删除图片成功')
      } else {
        message.error('删除图片失败')
      }
    }
    // 在操作过程中更新fileList状态
    this.setState({ fileList })
  }

  render() {
    const { previewVisible, previewImage, fileList, previewTitle } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    return (
      <>
        <Upload
          action="/manage/img/upload"
          accept="image/*" 
          name="image"
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        >
          {fileList.length >= 3 ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </>
    )
  }
}
